//
//  Bundle+Localization.swift
//  Sample
//
//  Created by mac on 2025/7/11.
//  Copyright © 2025 Roy Marmelstein. All rights reserved.
//

import Foundation

extension Bundle {
    /// 从 Localizable.strings 文件中提取所有 key-value 映射
    func loadLocalizedStrings(for language: String) -> [String: String] {
        guard let path = self.path(forResource: "Localizable", ofType: "strings", inDirectory: "\(language).lproj"),
              let dict = NSDictionary(contentsOfFile: path) as? [String: String] else {
            return [:]
        }
        return dict
    }
    
    /// 通过 value 反查 key
    func findKey(for value: String, in language: String) -> String? {
        let dict = loadLocalizedStrings(for: language)
        return dict.first { $0.value == value }?.key
    }
    
    /// 通过 key 获取指定语言的翻译
    func localizedString(for key: String, language: String) -> String {
        guard let path = self.path(forResource: "Localizable", ofType: "strings", inDirectory: "\(language).lproj"),
              let dict = NSDictionary(contentsOfFile: path) as? [String: String] else {
            return key // 回退到 key
        }
        return dict[key] ?? key
    }
}
